package core;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Random;

public class Room {
	/* How big can be the room */
	private static final int MIN_LONG_SIDE = 10;
	private static final int MAX_LONG_SIDE = 25;
	private static final int MIN_SHORT_SIDE = 10;
	private static final int MAX_SHORT_SIDE = 20;

	/* How big is the room */
	private int longSide;
	private int shortSide;

	private ArrayList<Wall> limits = new ArrayList<Wall>();

	/* Where is the entrance and the exit */
	private Door entrance;
	private Door exit;

	/* Matrix of all the elements of the room */
	private Element matrix[][];

	public Room() {
		super();
		Random randomGen = new Random();
		longSide = MIN_LONG_SIDE
				+ randomGen.nextInt(MAX_LONG_SIDE - MIN_LONG_SIDE);
		shortSide = MIN_SHORT_SIDE
				+ randomGen.nextInt(MAX_SHORT_SIDE - MIN_SHORT_SIDE);
		matrix = new Element[shortSide][longSide];
		entrance = new Door(longSide, shortSide);
		this.addElement(entrance);
		exit = new Door(entrance.getPos(), longSide, shortSide);
		this.addElement(exit);
		for (int i = 0; i < (longSide * shortSide); i++) {
			if (((i != (entrance.getPos())) && (i != (exit.getPos())))
					&& (((i / longSide == 0)
							|| (i / longSide == (shortSide - 1))
							|| (i % longSide == 0) || (i % longSide == (longSide - 1))))) {
				Wall w = new Wall(i, longSide, shortSide);
				limits.add(w);
				this.addElement(w);
			}
		}
	}

	public int getLongSide() {
		return longSide;
	}

	public int getShortSide() {
		return shortSide;
	}

	public ArrayList<Wall> getLimits() {
		return limits;
	}

	public Door getEntrance() {
		return entrance;
	}

	public Door getExit() {
		return exit;
	}

	public Element[][] getMatrix() {
		return matrix;
	}

	public Element getElement(int x, int y) {
		return matrix[x][y];
	}

	public void addElement(Element e) {
		intAddElement(e);
	}

	public void removeElement(Element e) {
		intRemoveElement(e);
	}

	private void intAddElement(Element e) {
		matrix[e.getPos() / longSide][e.getPos() % longSide] = e;
	}

	private void intRemoveElement(Element e) {
		matrix[e.getPos() / longSide][e.getPos() % longSide] = null;
	}

	@Override
	public String toString() {
		return "Room [longSide=" + longSide + ", shortSide=" + shortSide
				+ ", limits=" + limits + ", entrance=" + entrance + ", exit="
				+ exit + ", matrix=" + Arrays.toString(matrix) + "]";
	}
}
